<?php
/**
 * Created by PhpStorm.
 * User: Edward
 * Date: 2019/5/31
 * Time: 13:23
 */

namespace app\admin\controller\user;


use app\admin\BaseController;
use app\admin\model\Area as AreaModel;
use app\common\controller\UtilCommon;
use app\lib\exception\FailedException;

/**
 * 地图方法(高德)
 * Class Area
 * @package app\admin\controller\user
 */
class Area extends BaseController{
    /**
     * 添加地图数据库
     * @return \think\response\Json
     * @throws \Exception
     */
    public function getDataAction(){
        set_time_limit(0);
        $url = "https://restapi.amap.com/v3/config/district?subdistrict=3&key=bb4198a1f146184af53322d424732f6b";
        $content = file_get_contents($url);
        $arr = json_decode($content, true);
        $area = $arr['districts'][0]['districts'];
        $data = $this->area($area);
        $areaService = new AreaModel();
        $areaService->where("1 = 1")->delete();
        $res = $areaService->insertAll($data);
        if (!$res) {
            throw (new FailedException(['msg' => '更新失败']));
        }
        return writeJson("200", "更新成功", "更新成功", "200");
    }

    /**
     * 高德地图JSON拆分
     * @param $districts
     * @param int $pid
     * @param array $data
     * @param int $index
     * @return array
     */
    private function area($districts, $pid = 0, &$data = array(), &$index = 0){
        foreach ($districts as $key => $value) {
            $obj['id'] = $value['adcode'];
            $obj['name'] = $value['name'];
            $obj['citycode'] = $value['level'] == "province" ? 0 : $value['citycode'];
            $obj['center'] = $value['center'];
            if($value['level'] == "province"){
                $obj['rank'] = 0;
            }else if($value['level'] == "city"){
                $obj['rank'] = 1;
            }else if($value['level'] == "district" || $value['level'] == "street"){
                $obj['rank'] = 2;
            }
            $obj['parent_id'] = $value['level'] == "province" ? 0 : $pid;
            if ($value['level'] == "street") {
                $index++;
                $obj['id'] = $value['adcode'] . "" . $index;
            }
            $data[] = $obj;
            $this->area($value['districts'], $value['adcode'], $data, $index);
        }
        return $data;
    }
}
